package com.tensquare.friend.intercepter;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by DUZEYU on 2018/12/25.
 */
@Component
public class JwtIntercepter implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("============================");
        String header = request.getHeader("Authorization");
        if (!header.startsWith("Bearer ")){
            throw new RuntimeException("权限不足！");
        }
        // 如果请求头不等于空
        if (null != header && !"".equals(header)){
            //解析请求头文件
            String token = header.substring(7);
            //对令牌进行验证
            try{
                Claims claims = jwtUtil.parseJWT(token);
                String role = (String) claims.get("roles");
                if (null != role || "admin".equals(role)){
                    request.setAttribute("claims_admin",claims);
                }
                if (null != role || "user".equals(role)){
                    request.setAttribute("claims_user",claims);
                }
            }catch (Exception e){
                throw new RuntimeException("令牌不正确！");
            }
        }
        return true;
    }
}
